[#003] 58. Length of Last Word


Posted by s1101192101 on 2021-05-12

  • link:
    leetcode

  • 解題思路:

    1. 從最後一個字元往前逐一尋找空白字元
    2. 增加若結尾字元是空白的例外處理

  • 程式碼:

/**
 * @param {string} s
 * @return {number}
 */
const lengthOfLastWord = function(s) {
    let k = s.length
    while(s[k-1]===' ') {
        k--;
    }

    for(var i=k-1; i>=0; i--) {
        if(s[i]===' ') break;
    }
    return k-1-i;
};


  • 結果:



#Leetcode #string #easy







Related Posts

[python] 關於python三兩事 - class,  __init__,   __call__

[python] 關於python三兩事 - class, __init__, __call__

Google python code style

Google python code style

How to build CICD with Jenkins as code based on container

How to build CICD with Jenkins as code based on container


Comments